// pages/workcard/index.ts
import UserApi from "../../api/UserApi"
import Toast from "tdesign-miniprogram/toast/index"
import AuthApi from "../../api/Auth"
import { BASE_URL } from "../../api/NetConfig"

const defaultAvatarUrl = "https://tdesign.gtimg.com/miniprogram/images/avatar1.png"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userId: 0,
    version: 0,
    nickname: "",
    phone: "",
    email: "",
    avatar: defaultAvatarUrl,
    avatarSrc: defaultAvatarUrl,
  },
  computed: {
    avatarSrc: function () {
      if (this.data.avatar.includes("http")) {
        return this.data.avatar
      } else {
        return BASE_URL + this.data.avatar
      }
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    let userInfo = wx.getStorageSync("user")
    if (userInfo) {
      this.setData({
        ...userInfo,
        avatarSrc: userInfo.avatar ? BASE_URL + userInfo.avatar : defaultAvatarUrl
      })
    }
    AuthApi.current().then((res: any) => {
      let userInfo = res.data[0]
      this.setData({
        ...userInfo,
        avatarSrc: userInfo.avatar ? BASE_URL + userInfo.avatar : defaultAvatarUrl
      })
    }).catch(e => {
      Toast({
        context: this,
        selector: '#t-toast',
        message: e,
      })
    })
  },
  onChooseAvatar(e: any) {
    const { avatarUrl } = e.detail
    this.setData({ avatar: avatarUrl, avatarSrc: avatarUrl })
  },
  async handleChangeAvatar() {
    const { avatar } = this.data
    if (avatar.includes('http://tmp/')) {
      await UserApi.changeAvatar(avatar)
    }
  },
  async handleConfirm() {
    try {
      await this.handleChangeAvatar()
    } catch {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '修改头像失败',
      })
      return
    }
    let { userId, version, nickname, phone, email } = this.data
    UserApi.update({ userId, version, nickname, phone, email }).then(_ => {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '提交成功',
        theme: 'success',
        direction: 'column',
      })
      wx.setStorageSync("user", { ...this.data })
      setTimeout(() => {
        wx.navigateBack()
      }, 300)
    }).catch(e => {
      Toast({
        context: this,
        selector: '#t-toast',
        message: e,
      })
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.onLoad()
  },
})
